package com.xingshang.util;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class MinioUtil implements FileStorageUtil {
    private final MinioClient minioClient;

    @Value("${minio.bucket.files}")
    private String bucketName;

    /**
     * 生成唯一文件名
     *
     * @param originalFilename 原始文件名
     * @return 唯一文件名
     */
    public String generateFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return uuid + extension;
    }

    /**
     * 获取文件的URL
     *
     * @param fileName 文件名
     * @return 文件URL
     * @throws Exception MinIO异常
     */

    public String getFileUrl(String fileName,String location) throws Exception {
        String path = location.concat("/").concat(getDefaultFolderPath()).concat(fileName);

        // 生成临时访问URL
        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(bucketName)
                        .object(location)
                        .method(Method.GET)
                        .expiry(7, TimeUnit.DAYS)
                        .build()
        );
        return url;
    }

    @Override
    public String uploadFile(MultipartFile file, String objectName,String location) throws Exception {
        String path = location.concat("/").concat(getDefaultFolderPath()).concat(objectName);

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(path)
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build()
        );
        String fileUrl = getFileUrl(objectName,location);
        int i = fileUrl.indexOf("?");
        return fileUrl.substring(0, i);
    }

    //获取文件默认存储目录路径 年/月/日
    public String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/") + "/";
        return folder;
    }
}
